package com.konsung.ksdc.manager.shop;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.netbean.CartDetailNetBean;
import com.konsung.ksdc.bean.netbean.ProductDetailNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.NumEditText;
import com.konsung.ksdc.config.MyApplication;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 购物车商品列表adapter
 * Created by Administrator on 2016/5/3 0003.
 */
public class BuyListAdapter extends BaseAdapter {

    private List<CartDetailNetBean> cartDetailNetBeanList;
    private Handler handler;

    public static final int MSG_UPDATE_SUM = 1; // 消息类型 更新

    private Activity activity;
    private ProductDetailNetBean productDetailNetBean;
    private String num;
    private int available; // 商品有效库存
    private boolean isZero = true; // 当商品库存为0，打个标记，防止进入死循环
    private List<CartDetailNetBean> selectedList = new ArrayList<>();
    private Map<Integer, Boolean> isCheckedList = new ConcurrentHashMap<>();

    /**
     * 构造方法
     * @param activity activity
     * @param list 购物车商品列表集合
     * @param handler handler对象
     */
    public BuyListAdapter(Activity activity, List<CartDetailNetBean> list,
            Handler handler) {
        cartDetailNetBeanList = list;
        this.activity = activity;
        this.handler = handler;
    }

    @Override
    public int getCount() {
        if (cartDetailNetBeanList != null) {
            return cartDetailNetBeanList.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return cartDetailNetBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {
        final CartDetailNetBean bean = cartDetailNetBeanList.get(position);
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(MyApplication.getContext())
                    .inflate(R.layout.item_product_for_cart, null);
            ButterKnife.bind(holder, convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.netAccount.setId(position); // 将position作为id与net控件绑定
        String picUrl = bean.getIconImageUrl();
        Picasso.with(MyApplication.getContext())
                .load(StringUtils.appendPicPath(picUrl))
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(holder.ivProduct);

        String title = bean.getProductName();
        holder.tvTitle.setText(title);

        String subtitle = bean.getSubTitle();
        holder.tvSubtitle.setText(subtitle);
        String price = bean.getMemberPrice();
        holder.tvPrice.setText("￥" + price);
        //存储购物车输入对应的数据，进入商品详情，与添加数量想加，对比是否超过库存
        String shopConut = cartDetailNetBeanList.get(holder.netAccount.getId()).getShopNumber();
        PreferenceUtils.putString(activity, bean.getProductName(), shopConut);
        holder.netAccount.getEtNum().setText(shopConut); // 显示对应id(position)的数据
        final ViewHolder finalHolder = holder;
        //增加事件拿出来，易传入id数据
        holder.netAccount.getAddBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finalHolder.netAccount.addAccount(bean.getProductId());
            }
        });
        /**
         * Text输入事件监听
         * 容易造成死循环，回调-监听—显示
         */
        holder.netAccount.getEtNum().addTextChangedListener(
                new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        final int id = finalHolder.netAccount.getId();
                        num = s.toString();

                        if (TextUtils.isEmpty(num)) {
                            return;
                        }
                        final int i = Integer.valueOf(num);

                        // 当+ -的时候重新储存本地购物车数量
                        PreferenceUtils.putString(activity, bean.getProductName(), num);

                        // 如果是已经为0
                        if (i == 0) {
                            ToastUtils.toastContent(activity, activity.getString(R.string
                                    .tip_cart_zero));
                            finalHolder.netAccount.setAccount(1);
                            isZero = false;
                            return;
                        }

                        getRepertory(bean.getProductId(), new IRepertory() {
                            @Override
                            public void getRespertory(ProductDetailNetBean productDetailNetBean) {
                                String repertory = productDetailNetBean.getRepertory();

                                /**
                                 *控制editext的数量控制
                                 */
                                if (Constants.isCartSubmit) {
                                    return;
                                }
                                if (!StringUtils.isEmpty(repertory) && !StringUtils.isEmpty(num)) {
                                    available = Integer.parseInt(repertory);
                                    // 存储对应的库存量
                                    PreferenceUtils.putInt(activity, bean.getProductId(),
                                            available);
                                    int count = Integer.parseInt(num);
                                    // 如果库存数量为0
                                    if (available == 0) {
                                        if (isZero) {
                                            ToastUtils.toastContent(activity, activity.getString(R
                                                    .string.tip_buy_exceed));
                                            finalHolder.netAccount.setAccount(1);
                                            isZero = false;
                                            notifiyUI();
                                        } else {
                                            // 不显示Editext,为true ，防止死循环
                                            isZero = true;
                                            notifiyUI();
                                        }
                                        return;
                                    }
                                    if (count > available) {
                                        ToastUtils.toastContent(activity, activity.getString(R
                                                .string.tip_buy_exceed));
                                        finalHolder.netAccount.setAccount(available);
                                        notifiyUI();
                                    } else {
                                        notifiyUI();
                                    }
                                }
                            }

                            // 更新UI
                            private void notifiyUI() {
                                // bean里的数据发生变化
                                cartDetailNetBeanList.get(id).setShopNumber(i + "");
                                Message msg = Message.obtain();
                                Bundle bundle = new Bundle();
                                int account = getProductAccount();
                                double sum = getProductSum();
                                bundle.putInt("account", account);
                                bundle.putDouble("sum", sum);
                                msg.setData(bundle);
                                msg.what = MSG_UPDATE_SUM;
                                handler.sendMessage(msg);
                            }
                        });
                    }
                }

        );

        holder.cbxSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (!selectedList.contains(bean)) {
                        selectedList.add(bean);
                        isCheckedList.put(position, true);
                    }
                    PreferenceUtils.getString(activity, bean.getProductName());
                    int num = Integer.valueOf(finalHolder.netAccount.getEtNum().getText()
                            .toString());
                    refreshUi(bean, num);
                } else {
                    selectedList.remove(bean);
                    isCheckedList.remove(position);
                    int num = Integer.valueOf(finalHolder.netAccount.getEtNum().getText()
                            .toString());
                    refreshUi(bean, num);
                }
            }
        });

        holder.llCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalHolder.cbxSelect.isChecked()) {
                    finalHolder.cbxSelect.setChecked(false);
                } else {
                    finalHolder.cbxSelect.setChecked(true);
                }
            }
        });
        Boolean isCheck = isCheckedList.get(position);
        if (null != isCheck && isCheck) {
            holder.cbxSelect.setChecked(true);
        } else {
            holder.cbxSelect.setChecked(false);
        }
        return convertView;
    }

    /**
     * 刷新界面
     * @param bean 购物车详情Bean
     * @param num 商品购买数量
     */
    private void refreshUi(CartDetailNetBean bean, int num) {
        bean.setShopNumber(num + "");
        Message msg = Message.obtain();
        Bundle bundle = new Bundle();
        int account = getProductAccount();
        double sum = getProductSum();
        bundle.putInt("account", account);
        bundle.putDouble("sum", sum);
        msg.setData(bundle);
        msg.what = MSG_UPDATE_SUM;
        handler.sendMessage(msg);
    }

    /**
     * 获取选中商品集合
     * @return 商品是否选中集合
     */
    public Map<Integer, Boolean> getIsCheckedList() {
        return isCheckedList;
    }

    /**
     * 获取购物车勾选商品bean集合
     * @return 购物车勾选的商品
     */
    public List<CartDetailNetBean> getSelectedList() {
        return selectedList;
    }

    /**
     * 适配器类
     */
    class ViewHolder {
        @Bind(R.id.iv_product)
        ImageView ivProduct;
        @Bind(R.id.tv_title)
        TextView tvTitle;
        @Bind(R.id.tv_price)
        TextView tvPrice;
        @Bind(R.id.tv_subtitle)
        TextView tvSubtitle;
        @Bind(R.id.net_account)
        NumEditText netAccount;
        @Bind(R.id.cbx_select)
        CheckBox cbxSelect;
        @Bind(R.id.ll_check)
        LinearLayout llCheck;
    }

    /**
     * 获取购物车列表集合
     * @return 购物车商品集合
     */
    public List<CartDetailNetBean> getData() {
        return cartDetailNetBeanList;
    }

    /**
     * 手动设置数据
     * @param data 购物车商品集合
     */
    public void setData(List<CartDetailNetBean> data) {
        cartDetailNetBeanList = data;
        notifyDataSetChanged();
    }

    /**
     * 获取到购物车中的所有商品数量
     * @return 购物车商品总数
     */
    public int getProductAccount() {
        int count = 0;
        if (selectedList == null) {
            return 0;
        }
        for (CartDetailNetBean bean : selectedList) {
            int number = Integer.parseInt(bean.getShopNumber());
            count += number;
        }
        return count;
    }

    /**
     * 获取到当前购物车所有商品总的花费
     * @return 购物车结算总金额
     */
    public double getProductSum() {
        double sum = 0;
        if (selectedList == null) {
            return 0;
        }
        int account = 0;
        double price = 0.0;
        for (CartDetailNetBean bean : selectedList) {
            account = Integer.parseInt(bean.getShopNumber());
            price = Double.parseDouble(bean.getMemberPrice());
            sum += (account * price);
        }
        return sum;
    }

    /**
     * 获取产品详情
     * @param productId 商品id
     * @param callback 回调
     */
    private void getRepertory(final String productId, final IRepertory callback) {
        RequestUtils.findProductDetailById(productId, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        if (resultCode.equals(Constants.REQUEST_OK)) {
                            productDetailNetBean = responseBean.getEntity(ProductDetailNetBean
                                    .class);
                            callback.getRespertory(productDetailNetBean);
                        }
                    }
                });
    }

    /**
     * 修改购买数量接口
     */
    private interface IRepertory {
        /**
         * 修改购买数量页面回调方法
         * @param productDetailNetBean 商品详情Bean
         */
        void getRespertory(ProductDetailNetBean productDetailNetBean);
    }

    /**
     * 全选操作，反选操作
     * @param count 购物车条目数量
     * @param isCheck 是否选择
     */
    public void setAllCheck(int count, boolean isCheck) {
        for (int i = 0; i < count; i++) {
            //便利购物车的数量
            if (isCheck) {
                //如果全选中
                if (!selectedList.contains(cartDetailNetBeanList.get(i))) {
                    //选中的list集合不包含该商品
                    selectedList.add(cartDetailNetBeanList.get(i));
                    isCheckedList.put(i, isCheck);
                }
            } else {
                //全部不选中
                selectedList.remove(cartDetailNetBeanList.get(i));
                isCheckedList.remove(i);
            }
        }
    }
}